<?php

namespace app\controllers;

use Yii;
use app\models\Project;
use app\models\ProjectSearch;
use app\models\Upfile;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use app\models\Member;
use app\models\UploadForm;
use yii\web\UploadedFile;

/**
 * ProjectController implements the CRUD actions for Project model.
 */
class ProjectController extends Controller {

    public $layout = 'main_1';

    public function behaviors() {
        return [
            'access' => [
                'class' => \yii\filters\AccessControl::className(),
                'rules' => [
                    [ 'allow' => true, 'roles' => ['@'],],
                ],
            ],
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['POST'],
                ],
            ],
        ];
    }

    /**
     * Lists all Project models.
     * @return mixed
     */
    public function actionIndex() {
        $searchModel = new ProjectSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

        //文件上传的model
        $uploadModel = new UploadForm();
        //导入文件
        if (\Yii::$app->request->isPost) {
            //使用yii2自带的文件上传
            $uploadModel->file = UploadedFile::getInstance($uploadModel, 'file');
            if ($uploadModel->file && $uploadModel->validate()) {
                if ($uploadModel->file->extension === "xls" || $uploadModel->file->extension === "xlsx") {
                    //文件存放路径
                    $path = 'uploads/' . $uploadModel->file->baseName . '.' . $uploadModel->file->extension;
                    $uploadModel->file->saveAs($path);


                    //使用PHPExcel库将Excel表中的数据存入数据库中
                    //读取Excel
                    $PHPReader = \PHPExcel_IOFactory::load($path);
                    //获取第一个Excel
                    $sheet = $PHPReader->getSheet(0);
                    // 取得总行数
                    $highestRow = $sheet->getHighestRow();
                    // 取得总列数
                    $highestColumm = $sheet->getHighestColumn();
                    //将总列数转换为数字

                    if (strlen($highestColumm) >= 2) {//列数大于26
                        $sub = substr($highestColumm, 1);
                        $colums = 26 + ord($sub) - ord('A') + 1;
                    } else {//列数小于26
                        $colums = ord($highestColumm) - ord('A') + 1; //ASCII转换
                    }

                    $model = new Project();
                    $attrs = $model->attributes;

                    //得到model的所有属性
                    foreach ($attrs as $key => $value) {
                        $attrsArr[] = $key;
                    }

                    //导入文件的字段与数据库的字段个数不一致,跳转到提示页面
                    $total = count($attrsArr) - 1;
                    if ($colums != $total) {
                        return $this->render('/upload/error_file');
                    }

                    /** 循环读取每个单元格的数据 */
                    //for ($row = 1; $row <= $highestRow; $row++) {//行数是以第1行开始
                    for ($row = 2; $row <= $highestRow; $row++) {//从第二行开始取，不要头部信息
                        $dataset = [];
                        for ($column = 'A', $j = 1; $column <= $highestColumm, $j <= $colums; $column++, $j++) {//列数是以A列开始
                            //使dataset数组的key与数据表中的字段对应
                            $key = $attrsArr[$j];
                            $dataset[$key] = $sheet->getCell($column . $row)->getValue();
                            // echo $column . $row . ":" . $sheet->getCell($column . $row)->getValue() . " ";
                        }
                        //echo "<br />";
                        $data[] = $dataset;
                    }

                    //将读取到的数组数据保存到数据库中
                    foreach ($data as $item) {
                        $projectno = $item['projectno'];
                        $temp = Project::find()->where(['projectno' => $projectno])->all();
                        //判断是否有记录，如果有，则删去原记录
                        if ($temp != null) {
                            $temp[0]->delete();
                        }
                        //保存新数据到数据库中
                        $model = new Project();
                        $model->setAttributes($item);
                        $model->save();
                    }
                }
            }
        }

        return $this->render('index', [
                    'searchModel' => $searchModel,
                    'dataProvider' => $dataProvider,
                    'model' => $uploadModel
        ]);
    }

    /**
     * Displays a single Project model.
     * @param string $id
     * @return mixed
     */
    public function actionView($id) {
        return $this->render('view', [
                    'model' => $this->findModel($id),
        ]);
    }

    /**
     * Creates a new Project model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate() {
        $model = new Project();

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            //获取前天传递的成员信息 并保存到数据库表member中 但是并没有把数据保存到project中 
            //所以要书写beforesave方法保存数据到project中以至于可以显示
            $members = Yii::$app->request->post('projectmember');
            Member::updateMembers($model->id, $members);
            return $this->redirect(['view', 'id' => $model->id]);

//            $model = new Project();
//             return $this->render('create', [
//                'model' => $model,
//            ]);
        } else {
            return $this->render('create', [
                        'model' => $model,
            ]);
        }
    }

    /**
     * Updates an existing Project model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param string $id
     * @return mixed
     */
    public function actionUpdate($id) {
        $model = $this->findModel($id);

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            $members = Yii::$app->request->post('projectmember');
            Member::updateMembers($model->id, $members);
            return $this->redirect(['view', 'id' => $model->id]);
        } else {
            return $this->render('update', [
                        'model' => $model,
            ]);
        }
    }

    //删除附件
    public function actionClose() {
        $fileid = Yii::$app->request->post('fileid');
        $upfile = Upfile::findOne(["id" => $fileid]);
        $res = "";
        if ($upfile->delete()) {
            $res = 1;
        } else {
            $res = 0;
        }
        echo json_encode(array('res' => $res));
    }

    /**
     * Deletes an existing Project model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param string $id
     * @return mixed
     */
    public function actionDelete($id) {
        $this->findModel($id)->delete();

        return $this->redirect(['index']);
    }

    /**
     * Finds the Project model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param string $id
     * @return Project the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id) {
        if (($model = Project::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }

}
